<template>
  <!-- <div>123</div> -->
  <div class="pie" ref="boxRef" :style="{height: `${props.height}px`,width:`${props.width}px`}"></div>
</template>
<script setup lang="ts">
import { onMounted, reactive, getCurrentInstance, ref, onUnmounted } from 'vue'
import type { EChartsOption, EChartsType } from "echarts";
import * as echarts from "echarts";
// const that = getCurrentInstance();
const props:IProps = defineProps({
  height:{
    type:Number,
    default:300
  },
  width:{
    type:Number,
    default:300
  },
  title:{
    type:String,
  }
})
interface IProps{
    title?:string
    data?:{
        value:number;
        name:string;
    }[],
    height:number
    width:number
}
let chart:echarts.ECharts|null=null
onMounted(() => {
  let myChart = document.getElementsByClassName('pie')[0]
  // let Chart = that?.proxy?.$echarts.init(myChart as HTMLDivElement)
  chart = echarts.init(myChart as HTMLDivElement)
  chart.setOption(option)
})
onUnmounted(()=>{
  if(chart){
    chart.dispose()
    chart=null
  }
})
    // 使用防抖函数处理窗口大小变化事件
    function debounce(fn: Function, delay: number) {
      let timer: ReturnType<typeof setTimeout>
      return function(this: any, ...args: any[]) {
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(() => {
          fn.apply(this, args)
        }, delay)
      }
    }
window.addEventListener('resize',debounce(()=>{
  if(chart){
    chart.resize()
  }
},200))
const option = reactive<EChartsOption>({
  // title:{
  //   show: Boolean(`${props.title}` )|| false,
  //   text: props.title,
  //   textStyle: {
  //         color: '#333'
  //       }
  // },
  title:{
    show: true,
    text: props.attrs.title,
    textStyle: {
          color: '#333'
        }
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: '5%',
    left: 'center'
  },
  series: [
    {
      name: 'Access From',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 40,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 1048, name: 'Search Engine' },
        { value: 735, name: 'Direct' },
        { value: 580, name: 'Email' },
        { value: 484, name: 'Union Ads' },
        { value: 300, name: 'Video Ads' }
      ]
    }
  ]
});

</script>
<style lang="scss" scoped></style>